# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtGui import QTextCharFormat
from PyQt5.QtGui import QTextDocument
from PyQt5.QtGui import QTextCursor
from PyQt5.QtGui import QColor
from PyQt5.QtGui import QIcon
from window import Ui_MainWindow
import sys

TOOL_VERSIONS = 'V1.2'

class GloabalUI(QMainWindow, Ui_MainWindow):  # 继承类
    app = QApplication(sys.argv)
    # 需要在其他线程中刷新的空间需要自定义信号刷新，否则可能报错
    serial_port_signal = QtCore.pyqtSignal(list, str)
    progress_bar_signal = QtCore.pyqtSignal(int)
    button_info_signal = QtCore.pyqtSignal(str)
    used_time_signal = QtCore.pyqtSignal(int)
    def __init__(self):
        super().__init__()
        self.setupUi(self)  # 执行类中的setupUi函数
        self.setWindowTitle(TOOL_VERSIONS)
        self.serial_port_signal.connect(self.renew_serial_port)
        self.progress_bar_signal.connect(self.renew_progreess)
        self.button_info_signal.connect(self.button_info)
        self.used_time_signal.connect(self.show_used_time)

    def renew_serial_port(self, port_list, cur):
        ''' 刷新串口列表
            port_list: 串口列表  类型: list
            cur : 当前要显示的端口 类型:str
            如果列表中没有 cur 端口则显示列表第一个
        '''
        self.serial_combo.clear()
        self.serial_combo.addItems(port_list)
        print(port_list)
        if cur in port_list:
            self.serial_combo.setCurrentText(cur)
        elif len(port_list) > 0:
            self.serial_combo.setCurrentText(port_list[0])

    def renew_progreess(self, progreess):
        if progreess > 100:
            progreess = 100
        ui.progress_bar.setValue(progreess)

    def button_info(self, info):
        ui.update_button.setText(info)

    def show_used_time(self, tim_s):
        ui.used_time.setText("used time: {} S".format(tim_s))


ui = GloabalUI()
